#include "stdafx.h"
#include "fcgi_server_t.h"
#include "handle_request.h"
/** 
 * Initialize all needed data
 * 
 * @param port to listen on, by default - 10001
 */
fcgi_server_t::fcgi_server_t(int port, std::ostream& logger)
      :  logger_(logger)
      ,  port_(port)
      ,  stop_(false)
{}

void fcgi_server_t::stop()
{
    stop_ = true;
}

int fcgi_server_t::run_sync()
{
   logger_ << "Starting fcgi server at localhost: " << port_ << std::endl;
   fcgi::service service;
   fcgi::acceptor acceptor(service, port_);
   int status = 0;
   try 
   {
      while(!status && !stop_)
      {
         status = acceptor.accept(&handle_request);
      }
      return status;
   }
   catch(boost::system::system_error const& se)
   {
      // This is the type of exception thrown by the library.
      std::cerr<< "[fcgi] System error: " << se.what() << std::endl;
      return -1;
   }
   catch(std::exception const& e)
   {
      // Catch any other exceptions
      std::cerr<< "[fcgi] Exception: " << e.what() << std::endl;
      return -2;
   }
   catch(...)
   {
      std::cerr<< "[fcgi] Uncaught exception!" << std::endl;
      return -3;
   }
}
